use reqwest::Client;
use serde::{Deserialize, Serialize};
// use serde_json::json;
use std::error::Error;

#[derive(Debug, Serialize, Deserialize)]
pub struct Message {
    pub role: String,
    pub content: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ChatRequest {
    pub model: String,
    pub messages: Vec<Message>,
    pub enable_enhancement: bool,
}

pub async fn send_chat_request(
    messages: Vec<Message>,
) -> Result<String, Box<dyn Error>> {
    let config = crate::config::load_config()?;
    let client = Client::new();

    let request_body = ChatRequest {
        model: config.model,
        messages,
        enable_enhancement: config.enable_enhancement,
    };

    log::info!("Sending request to: {}", config.ai_url);
    log::info!("Request body: {:?}", request_body);

    let response = client
        .post(config.ai_url)
        .header("Content-Type", "application/json")
        .header("Authorization", format!("Bearer {}", config.api_key))
        .json(&request_body)
        .send().await?;

    let response_text = response.text().await?;
    log::info!("Received response: {}", response_text);

    Ok(response_text)
}